package fe;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;

import utils.Utils;
import extractor.BaseRecord;

public class FeatureManager {
	public static final String FEATURE_SEPARATOR = ",";
	private FeatureExtractorBase[] featureExtractors = null;
	private HashMap<String, FeatureExtractorBase> featureMap;
	
	
	public void initManager(String featureConfig, String seperator) throws Exception{
		String[] featureNames = featureConfig.split(seperator);
		featureExtractors = new FeatureExtractorBase[featureNames.length];
		featureMap = new HashMap<String, FeatureExtractorBase>();
		for (int i = 0; i < featureNames.length; ++i) {
			featureExtractors[i] = createFeatureExtractorByName(featureNames[i]);
			featureExtractors[i].initFeature();
			featureMap.put(featureExtractors[i].getClass().getName(), featureExtractors[i]);
		}
		
	}
	
	public FeatureExtractorBase getFeatureExtractorByName(String name) {
		return featureMap.get(name);
	}
	
	@SuppressWarnings("unchecked")
	private FeatureExtractorBase createFeatureExtractorByName(String featureName) throws Exception{
		FeatureExtractorBase base;
		Class cls = Class.forName(featureName);
		Constructor ct = cls.getConstructor(new Class[]{this.getClass()});
		base = (FeatureExtractorBase)ct.newInstance(new Object[]{this});
		return base;
	}
	public void beginRequest() {
		for (FeatureExtractorBase extractor : featureExtractors) {
			extractor.beginRequest();
		}
	}
	public void endRequest() {
		for (FeatureExtractorBase extractor : featureExtractors) {
			extractor.endRequest();
		}
	}
	public String getFeaturesStr(ArrayList<BaseRecord> records, int pos) throws Exception{
		String[] features = new String[featureExtractors.length];
		for (int i = 0; i < featureExtractors.length; ++i) {
			String value = featureExtractors[i].getFeature(records, pos);			
			if (featureExtractors[i].isNorminal()) {
				if (!Utils.isValid(value))
					value = "?";
				else 
					value = "'" + value.replace(",", "|").replace("'", "!").replace("\"", "`") + "'";				
			}
			
			features[i] = value;
		}
		return Utils.getRecord(features, FEATURE_SEPARATOR);
	}	
}
